package com.tledu.study_springboot.dao;

import com.tledu.study_springboot.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

// 这个注解就代表这一层是dao层
// 就是和数据库进行交互的
@Repository
public class StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void insert(Student student) {
        // 只操作这几个字段
        String sql = "insert into student(name,mobile,school_name) value (?,?,?)";
        // update执行写操作
        jdbcTemplate.update(sql,student.getName(),student.getMobile(),student.getSchoolName());
    }

    public List<Student> list() {
        String sql = "select * from student";
        // 查询出了所有的学生
        List<Map<String,Object>> studentListMap = jdbcTemplate.queryForList(sql);
        // 吧Map转成Student
        List<Student> students = new ArrayList<>();
        for (Map<String, Object> map : studentListMap) {
            // 构建学生对象
            Student student = new Student();
            student.setId((Integer) map.get("id"));
            student.setName((String) map.get("name"));
            student.setMobile((String) map.get("mobile"));
            student.setSchoolName((String) map.get("school_name"));
            // 把这个学生对象放到学生数组中
            students.add(student);
        }
        return students;
    }
}
